/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.babystar.io
 *
 * 版权所有，侵权必究！
 */

package io.babystar.modules.app.controller;


import io.babystar.common.utils.DateUtils;
import io.babystar.common.utils.R;
import io.babystar.modules.business.entity.*;
import io.babystar.modules.business.service.*;
import io.babystar.modules.sys.controller.AbstractController;
import io.babystar.modules.sys.entity.SysUserEntity;
import io.babystar.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 个人中心
 *
 * @author whc
 * @email
 * @date 2021-03-23 15:31
 */
@RestController
@RequestMapping("/app")
@Api("个人中心")
public class AppMyController extends AbstractController {

    @Autowired
    private SignService signService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private ParentService parentService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private CourseDateService courseDateService;
    @Autowired
    private CourseStudentService courseStudentService;
    @Autowired
    private StudentCourseDateService studentCourseDateService;

    /**
     * 教练签到
     * @param studentId
     * @param teacherId
     * @param teacherName
     * @param surplus
     * @param
     * @return
     */
    @GetMapping("/signIn")
    @ApiOperation("签到")
    public R signIn(String studentId,String teacherId,String teacherName,String surplus,String scdId) {
        try{
            StudentCourseDateEntity scdEntity =  studentCourseDateService.getById(scdId);
            Integer status = scdEntity.getStatus();
            if(1 == status){
                return R.ok("学员已签到，请勿重复操作！");
            }

            SignEntity t = new SignEntity();
            t.setStudentId(Integer.parseInt(studentId));
            t.setCourseId(scdEntity.getCourseId());
            if (StringUtils.isNotEmpty(teacherId)) {
                t.setTeacherId(Integer.parseInt(teacherId));
                t.setTeacherName(teacherName);
            }
            t.setSignTime(new Date());
            t.setSurplus(surplus);
            t.setCourseTimeId(Integer.parseInt(scdId));
            //预约签到
            t.setSource("1");
            return signService.signIn(t, scdEntity);
            /*
            boolean sign = signService.signIn(t,scdEntity);
            if(sign){
                return R.ok();
            }else {
                return R.error("没有剩余课时");
            }*/
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok();
    }




    /**
     * 选择孩子
     * @param parentId
     * @return
     */
    @GetMapping("/chooseStudent")
    public R chooseStudent(String parentId){
        Map<String, Object> p = new HashMap<>();
        p.put("parent_id", parentId);
        List<StudentEntity> studentEntityList = studentService.listByMap(p);
        return R.ok().put("studentEntityList",studentEntityList);
    }

    /**
     * 查孩子详情
     * @param id
     * @return
     */
    @RequestMapping("/queryStudent")
    public R queryStudent(String id) {
        StudentEntity studentEntity = studentService.getById(id);
        Integer parentId = studentEntity.getParentId();
        ParentEntity parentEntity = parentService.getById(parentId);

        Map<String, Object> p = new HashMap<>();
        p.put("student_id", studentEntity.getId());
        List<CourseStudentEntity> courseList = courseStudentService.listByMap(p);

        String course = "";
        for(CourseStudentEntity cs : courseList){
            CourseEntity courseEntity = courseService.getById(cs.getCourseId());
            if(courseEntity!=null){
                course += courseEntity.getName() + ",";
            }
        }
        if(course.length()>0){
            course = course.substring(0, course.length()-1);
        }

        return R.ok().put("studentEntity", studentEntity)
                .put("parentEntity", parentEntity)
                .put("course", course);
    }

    /**
     * 家长预约
     * @param studentId
     * @param courseId
     * @param courseTimeId
     * @param courseTimeDesc
     * @return
     */
    @GetMapping("/appoint")
    public R appoint(String studentId,String courseId,String courseTimeId,String courseTimeDesc) {
        //if (StringUtils.isNotEmpty(courseTimeDesc)) {
            Map<String, Object> p = new HashMap<>();
            p.put("course_id", courseId);
            p.put("student_id", studentId);
            p.put("course_time_id", courseTimeId);
            p.put("course_time_desc", courseTimeDesc);
            List<StudentCourseDateEntity> list = studentCourseDateService.listByMap(p);
            if (list != null && list.size() > 0) {
                return R.error("该课程已经预约过！");
            }
            //查询当前课程已经预约的人数
            Map<String, Object> p2 = new HashMap<>();
            p2.put("course_id", courseId);
            p2.put("course_time_id", courseTimeId);
            p2.put("course_time_desc", courseTimeDesc);
            List<StudentCourseDateEntity> list2 = studentCourseDateService.listByMap(p2);
            //查询系统设置人数
            CourseEntity course = courseService.getById(courseId);
            Integer limitsNum = course.getLimitsNum();
            if (list2 != null && limitsNum != null && list2.size() >= limitsNum) {
                return R.error("课程已经约满！");
            }

            CourseDateEntity courseDateEntiy = courseDateService.getById(courseTimeId);
            String _cid = courseDateEntiy != null ? courseDateEntiy.getCourseId() + "" : "-1";
            if (!courseId.equals(_cid)) {
                return R.error("请重新选课预约！");
            }

            ShopEntity shopEntity = shopService.getById(course.getShopId());
            Integer preLimit = shopEntity.getPreLimit();
            if(preLimit!=null && preLimit>0){
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date newDate = DateUtils.addDateMinutes(new Date(), preLimit);
                    Date courseDate = sdf.parse(DateUtils.format(new Date()) + " " + courseDateEntiy.getStartTime() + ":00");
                    if(newDate.getTime()>courseDate.getTime()){
                        return R.error("开课前"+preLimit+"分钟不能约课！");
                    }
                }catch (ParseException e){
                    e.printStackTrace();
                    return R.error("约课异常");
                }
            }


            //根据type和level判断1.可选课程等级（例中级课程可向下选择初级和启蒙课程）；2.特殊课程type为1，则都可以选取。
            Integer type = course.getType();
            if(type!=null && type.intValue()==1){
                //type==1 可以约课
            }else{
                Map<String, Object> p4 = new HashMap<>();
                p4.put("student_id", studentId);
                List<CourseStudentEntity> studentCourse = courseStudentService.listByMap(p4);
                boolean flag = false;
                String errMsg = "";
                for(CourseStudentEntity stc: studentCourse) {
                    //当前学生的报名的课程
                    CourseEntity stuCourse = courseService.getById(stc.getCourseId());
                    if(stuCourse==null){
                        return R.error("请联系教练添加课程！");
                    }
                    //int stuLevel = stuCourse.getLevel();
                    long stuCourseId = stuCourse.getId();
                    errMsg = stuCourse.getName();

                    //预约的课程
                    //int yuyLevel = course.getLevel();
                    long yuyCourseId = course.getId();

                    //if (stuCourseId == yuyCourseId || stuLevel >= yuyLevel) {
                    if (stuCourseId == yuyCourseId) {
                        flag = true;
                    }
                }
                if(!flag){
                    return R.error("只能预约"+errMsg+"课程");
                }
            }
        //}
        StudentEntity student = studentService.getById(studentId);
        Integer residualClassHour = student.getResidualClassHour();
        if (residualClassHour == null || residualClassHour.intValue() < 1) {
            return R.error("剩余课时不足，无法预约课程！");
        }
        //验证到期日期
        Date dueTime = student.getDueTime();
        Date nowTime = new Date();
        if (dueTime.before(nowTime)) {
            return R.error("课程已到期！");
        }

        int cshopId = course.getShopId();
        int sshopId = student.getShopId();
        if (cshopId!=sshopId) {
            return R.error("不能跨校区约课！");
        }

        //每周最大预约数
        String yuyueDate = courseTimeDesc.substring(0,10);
        Map<String, Object> p3 = new HashMap<>();
        p3.put("student_id", studentId);
        p3.put("start", DateUtils.getMonDay(yuyueDate));
        p3.put("end", DateUtils.getSunDay(yuyueDate));
        Integer appointCount = studentCourseDateService.getStudentAppointCount(p3);
        if(appointCount!=null && student.getWeekLimit()!=null && appointCount.intValue()>student.getWeekLimit()){
            return R.error("每周限约"+student.getWeekLimit()+"次课");
        }

        //预约课程
        StudentCourseDateEntity t = new StudentCourseDateEntity();
        t.setBusinessId(student.getBusinessId());
        t.setStudentId(Integer.parseInt(studentId));
        t.setCourseId(Integer.parseInt(courseId));
        t.setCourseTimeId(Integer.parseInt(courseTimeId));
        t.setCourseTimeDesc(courseTimeDesc);
        t.setStatus(0);
        t.setCreateTime(new Date());
        studentCourseDateService.save(t);

        return R.ok("预约成功");
    }

    /**
     * 我的
     */
    @GetMapping("/my")
    @ApiOperation("个人中心")
    public R my(String id) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Map<String, Object> map = new HashMap<>();
        SysUserEntity sysUser = sysUserService.getById(id);
        if(sysUser==null){
            return R.error("无此用户信息！");
        }
        if(sysUser.getParentTeacherId()!=null){
            //查询学生基本信息
            Map<String, Object> p = new HashMap<>();
            p.put("parent_id", sysUser.getParentTeacherId());
            List<StudentEntity> studentList = studentService.listByMap(p);
            if(studentList !=null && studentList.size()>0){
                StudentEntity student = studentList.get(0);
                String dueTimeStr = "";
                map.put("student", student);
                Date dueTime = student.getDueTime();
                if(dueTime!=null) {
                    dueTimeStr = sdf.format(dueTime);
                    map.put("dueTimeStr", dueTimeStr);
                }else{
                    map.put("dueTimeStr", sdf.format(new Date()));
                }

                //2.查询学生课程
                Map<String, Object> params = new HashMap<>();
                params.put("student_id", student.getId());
                List<CourseStudentEntity> list = courseStudentService.listByMap(params);
                Integer courseId = null;
                if (list != null && list.size() > 0) {
                    CourseStudentEntity courseStudentEntity = list.get(0);
                    courseId = courseStudentEntity.getCourseId();
                    map.put("courseStudent", courseStudentEntity);
                }

                if(courseId!=null) {
                    //3.查询课程
                    Map<String, Object> cparams = new HashMap<>();
                    cparams.put("id", courseId);
                    List<CourseEntity> courseList = courseService.listByMap(cparams);
                    if (courseList != null && courseList.size() > 0) {
                        map.put("course", courseList.get(0));
                    }

                    //4.查询课程上课时间
                    Map<String, Object> dparams = new HashMap<>();
                    dparams.put("course_id",courseId);
                    List<CourseDateEntity> courseDateEntityList = courseDateService.listByMap(dparams);
                    map.put("courseDate", courseDateEntityList);
                }
            }
            map.put("studentList",studentList);
            return R.ok(map);
        }else{
            return R.error("未配置业务ID，请联系管理员！");
        }
    }


    /**
     * 按店铺查询学生
     * @param shopId
     * @return
     */
    @RequestMapping("/getStudentListByShopId")
    public R getStudentListByShopId(String shopId, String keyword){
        Map<String, String> p = new HashMap<>();
        p.put("shopId",shopId);
        p.put("keyword",keyword);
        List<Map<String,Object>> studentEntityList = studentService.getStudentByShopId(p);
        return R.ok().put("studentList",studentEntityList);
    }

    @RequestMapping("/getSignCount")
    public R getSignCount(String studentId){
        Map<String, Object> p = new HashMap<>();
        p.put("student_id",studentId);
        List<SignEntity> signEntityList = signService.listByMap(p);
        return R.ok().put("signCount",signEntityList.size());
    }

    @RequestMapping("/getBusinessInfo")
    public R getBusinessInfo(String bid){
        BusinessEntity businessEntity = businessService.getById(bid);
        return R.ok().put("business",businessEntity);
    }


    @RequestMapping("/test")
    public R test(String bid){
        System.out.println("1111111111");
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("222222222222");
        return R.ok().put("msg",1111);
    }

}
